#include <cctype>
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <sstream>
#include <algorithm>
struct Record
{
    Record(const std::string word, int frequency)
        : _word(word), _frequency(frequency)
    {
    }
    std::string _word;
    int _frequency;
};
bool operator<(const Record &lhs, const Record &rhs)
{
    return lhs._word < rhs._word;
}
class Dictionary
{
public:
    Dictionary(int size)
    {
        _dict.reserve(size);
    }
    void read(const std::string &filename)
    {
        std::ifstream ifs(filename);
        if (!ifs)
        {
            std::cerr << "ifstream open file failed" << std::endl;
            return;
        }
        std::string line;
        while (std::getline(ifs, line))
        {
            std::istringstream iss(line);
            std::string word;
            while (iss >> word)
            {
                dealWord(word);
                insert(word);
            }
        }
        sort(_dict.begin(), _dict.end());
        ifs.close();
    }
    void dealWord(std::string &word)
    {
        auto it = word.begin();
        while (it != word.end())
        {
            if (!isalpha(*it))
            {
                it = word.erase(it);
            }
            else
            {
                ++it;
            }
        }
    }
    void insert(const std::string &word)
    {
        if (word.size() == 0)
        {
            return;
        }
        size_t idx = 0;
        for (; idx < _dict.size(); idx++)
        {
            if (word == _dict[idx]._word)
            {
                ++_dict[idx]._frequency;
                break;
            }
        }
        if (idx == _dict.size())
        {
            _dict.push_back(Record(word, 1));
        }
    }
    void store(const std::string &filename)
    {
        std::ofstream ofs(filename);
        if (!ofs)
        {
            std::cerr << "ofstream open file failed" << std::endl;
            return;
        }
        for (auto &re : _dict)
        {
            ofs << re._word << " " << re._frequency << std::endl;
        }
        ofs.close();
    }

private:
    std::vector<Record> _dict;
};
void test()
{
    Dictionary d1(500);
    d1.read("dic.txt");
    d1.store("diccat.txt");
}
int main(int argc, char *argv[])
{
    test();
    return 0;
}